package xyz.jcat.sco.admin.oauth2.server.auth;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import xyz.jcat.common.web.Resp;
import xyz.jcat.common.web.RespCodeMsg;

@Component
public class WebResponseExceptionTranslatorImpl implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        RespCodeMsg respCodeMsg = getRespCodeMsg(e);
        return ResponseEntity.ok(Resp.fail(respCodeMsg));
    }

    private RespCodeMsg getRespCodeMsg(Exception e) {
        RespCodeMsg respCodeMsg = RespCodeMsg.TIME_OUT;
        if(e instanceof HttpRequestMethodNotSupportedException) {
            respCodeMsg = RespCodeMsg.METHOD_NOT_SUPPORTED;
        } else if(e instanceof InvalidGrantException) {
            respCodeMsg = RespCodeMsg.ACCOUNT_OR_PWD_ERROR;
        } else if(e instanceof AuthenticationException) {
            respCodeMsg = RespCodeMsg.UNAUTHORIZED;
        } else if(e instanceof AccessDeniedException) {
            respCodeMsg = RespCodeMsg.FORBIDDEN;
        }
        return respCodeMsg;
    }

}
